package com.heima.article.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ArticleCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ArticleCollectionServiceImpl implements ArticleCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult articleCollection(CollectionBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getOperation() == 0 && cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + apUser.getId(), dto.getEntryId().toString()) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "您已收藏过了！");
        }
        if (dto.getOperation() == 0) {
            log.info("文章收藏，保存key:{},{},{}", dto.getEntryId(), apUser.getId().toString(), JSON.toJSONString(dto));
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + apUser.getId(), dto.getEntryId().toString(), JSON.toJSONString(dto));
        } else {
            //取消收藏
            log.info("文章收藏，删除key:{},{},{}", dto.getEntryId(), apUser.getId().toString(), JSON.toJSONString(dto));
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + apUser.getId(), dto.getEntryId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.NO_ALERT_INFO);
    }
}
